<template>
  <div class="box">
    <div class="nav">
      <div class="nav-item" 
        v-for="(item,index) in navItems" 
        :key="index" 
        @click="changeActive(index)"
        :style="active == index ? 'color:#0f4494;font-weight:bold' : ''"
      >
        {{item.name}}
        <div class="line" :class="{'active':index == active}"></div>
      </div>
    </div>
    <div class="chartsbox" ref="chart" v-loading="loading"></div>
  </div>
</template>
<script>
import { useApi } from '../../utils/api'
export default {
  props: {
    navItems: {
      type: [Array],
      default: [],
      
    },
  },
  data(){
    return{
      active:0,
      series: {},
      loading:false,
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    changeActive(index) {
      console.log(this.navItems[index]);
      this.active = index;
      this.getData();
    },
    // 获取数据
    async getData() {
      // if(this.loading){
      //   return;
      // }
      this.loading = true;
      const data = await $fetch(
        `/net/web/avgPrice/getAvgPriceData`,
        { 
          method: 'Get',
          params: { breedId: this.navItems[this.active].id} 
        }
      );
      console.log(data);
      let rawData = data.result;
      // 收集所有可能的 yearDate（去重）
      if(rawData.length > 0 && Array.isArray(rawData[0])){
        console.log('多数据');
        const allDates = [...new Set(rawData.flat().map(item => item.yearDate))].sort();
        console.log('所有日期列表',allDates);
        const series = rawData.map(breedData => {
          const dateToValue = new Map(breedData.map(item => [item.yearDate, item.value]));
          return {
            name: breedData[0].childKind,
            type: "line",
            connectNulls: true,
            data: allDates.map(date => dateToValue.get(date) || null), // 缺失数据补 null
            showSymbol: false
          };
        });
        console.log('数据补齐',series);
        this.loading = false;
        this.series = series;
        this.initChart(allDates);
        
      }else{
        console.log('单数据');
        let allDates = rawData.map(obj => obj.yearDate);
        const value = rawData.map(obj => obj.value);
        console.log('所有日期列表',allDates);
        const series = {
            name: rawData[0].childKind,
            type: "line",
            connectNulls: true,
            data: value, // 缺失数据补 null
            showSymbol: false
        };
        this.series = series;
        this.initChart(allDates);
        console.log('数据集',series);
        this.loading = false;
      }
    },
    initChart(allDates) {
      const chart = this.$echarts.init(this.$refs.chart);
      chart.clear();
      this.loading = false;
      chart.setOption({
        grid:{
          x:10,
          y:10,
          x2:10,
          y2:10
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            // console.log('数据信息',params);
            let result = '';
            params.forEach(item=>{
              result += item.marker + item.axisValue + item.seriesName + '<br>'
            })
            return result;
          }
        },
        xAxis: { type: "category", data: allDates },
        yAxis: { 
          type: "value",
          min: (value)=>{
            return Math.floor(value.min / 100)*100-100
          },
          max: (value)=>{
            return Math.ceil(value.max / 100)*100+100
          },
        },
        series: this.series,
      });
      // 响应式调整大小
      // window.addEventListener('resize', () => chart.resize());
    },
  },
  beforeDestroy() {
    // 组件销毁时移除监听器
    window.removeEventListener('resize', this.resizeHandler);
  },
};
</script>

<style lang="scss" scoped>
  .box{
    height: 166px;
    background-color: #fafafa;
    .nav{
      width: 100%;
      height: 32px;
      background-color: #f0f6fa;
      display: flex;
      .nav-item{
        width: 20%;
        text-align: center;
        line-height: 30px;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        align-items: center;
        .line{
          width: 56px;
          height: 2px;
          background-color: #f0f6fa;
        }
        .active{
          background-color: #0f4494;
        }
      }
    }
    .chartsbox{
      width: 100%;
      height: 132px;
      // background-color: #eee;
    }
  }
</style>